package gold.digger;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC200 {

    public int numIslands(char[][] grid) {
        if (null == grid || grid.length <= 0) {
            return 0;
        }


        int m = grid.length, n = grid[0].length, count = 0;
        boolean[][] visited = new boolean[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == '1' && !visited[i][j]) {
                    ++count;
                    DFSLand(grid, visited, i, j);
                }
            }
        }

        return count;
    }

    public void DFSLand(char[][] grid, boolean[][] visited, int x, int y) {
        if (x > grid.length - 1 || x < 0 || y < 0 || y > grid[0].length - 1 || grid[x][y] != '1' || visited[x][y]) {
            return;
        }

        visited[x][y] = true;
        DFSLand(grid, visited, x + 1, y);
        DFSLand(grid, visited, x - 1, y);
        DFSLand(grid, visited, x, y + 1);
        DFSLand(grid, visited, x, y - 1);
    }

    public static void main(String[] args) {
        LC200 an = new LC200();
        char grid[][] = {
                {'1', '1', '0', '0', '0',},
                {'1', '1', '0', '0', '0',},
                {'0', '0', '1', '0', '0',},
                {'0', '0', '0', '1', '1',},
        };
        System.out.println(an.numIslands(grid));
    }
}
